import { useDispatch } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
import type { Reducer, AnyAction } from '@reduxjs/toolkit'

import {
    persistStore, persistReducer,
    // FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER
} from 'redux-persist'

import storage from 'redux-persist/lib/storage' //  实现本地存储的模块
import { userStore, signStore, applyStore, remindStore } from './modules'
import type { UsersState } from './modules/userStore'
import type { PersistPartial } from 'redux-persist/es/persistReducer'

const persistConfig = {
    key: 'root', // key 的名字
    version: 1, // 版本多少
    storage, //  是否使用 storage 做存储
    whitelist: [ 'token' ] // 指定模块的某个数据持优化
}
const store = configureStore( {
    reducer: {
        userStore: persistReducer( persistConfig, userStore ) as Reducer<UsersState & PersistPartial, AnyAction>,// 模块数据持久化
        signStore,
        applyStore,
        remindStore,
    },
    middleware: ( getDefaultMiddleware ) =>
        getDefaultMiddleware( {
            serializableCheck: false
            // serializableCheck: { // 内部 dispatch 执行
            //     ignoredActions: [ FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER ]
            // }
        } )
} )

persistStore( store )
// 导出 store 类型
export type RootState = ReturnType<typeof store.getState>

// 导出 异步方法的ts限制
export type AppDispatch = typeof store.dispatch
export const useAppDispatch: () => AppDispatch = useDispatch

export default store
